package com.usoft.thrift.monitor;

import com.usoft.thrift.exception.ThriftException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * Created by xinxingegeya on 16/3/3.
 */
public class ServiceMonitorProxyHandler implements InvocationHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 被代理的服务实现类
     */
    private Object serviceImpl;

    private ServiceMonitorInfo monitorInfo;

    public ServiceMonitorProxyHandler(Object serviceImpl,
            ServiceMonitorInfo monitorInfo) {
        this.serviceImpl = serviceImpl;
        this.monitorInfo = monitorInfo;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        long startTime = System.nanoTime();
        Object result;
        try {
            result = method.invoke(serviceImpl, args);
        } catch (Exception e) {
            monitorInfo.updateBizMethodInvokeInfo(method.getName(), false, 0);
            throw new ThriftException(e.getMessage(), e);
        }
        long endTime = System.nanoTime();
        long invokeTime = endTime - startTime;
        monitorInfo.updateBizMethodInvokeInfo(method.getName(), true,
            invokeTime);
        return result;
    }
}
